#-*- coding: utf-8 -*-
# Soi cầu xổ số

import re, os
import hashlib
import time, datetime
import traceback
import cStringIO as StringIO
from pymongo import Connection
from termcolor import cprint


conn = Connection('beta.mana.vn', 27017)    

def getMD5Hash(textToHash=None):
    return hashlib.md5(textToHash).hexdigest()

def soiCauXoSo():
    dsXS = ['XSTD','XSAG','XSBD','XSBP','XSBTH','XSBL','XSBTR','XSCM','XSCT','XSHG','XSHCM','XSKG','XSLA','XSST','XSTG','XSTV','XSTN','XSVL','XSVT','XSDL','XSDN','XSDT','XSBDH','XSDLK','XSGL','XSKH','XSKT','XSNT','XSPY','XSQB','XSQNM','XSQNI','XSQT','XSTTH','XSDNG','XSDNO']
    #db = conn['xoso']
    #print dsXS[0]
    doc = {}
    for i in range(0, len(dsXS)-1):
        db = conn['xoso']
        coll = db['ketquacau']
        tenXS = dsXS[i]
        doc['xoso'] = tenXS
        #print tenXS
        collection = db[tenXS]
        #print "----", collection
        if (collection != None):
            listTemp = []
            listKq = []
            rows =  collection.find().sort('dateobj', -1).limit(4)
            for r in rows:
                listKq.append(r)
            c = []
            #print listKq[0]['dateobj']
            for g in listKq:
                db = g['DB']
                db = db[len(db)-2:len(db)]
                c.append(db)
                for iTest in range(1, 9):
                    test = g['G'+str(iTest)]
                    a = test.split("-")
                    for k in range(0,len(a)):
                        b = a[k]
                        if b != '':
                            b = b[len(b)-2:len(b)]
                            c.append(b)
            #print c
            sogiai = len(c)/4
            for row in listKq:
                temp = row['DB']+row['G1']+row['G2']+row['G3']+row['G4']+row['G5']+row['G6']+row['G7']+row['G8']
                #print temp
                temp = temp.replace('-', "") 
                listTemp.append(temp)
            #for item in range(0,len(listTemp)):
                #print "abcmdj---", listTemp[item]
            str1 = listTemp[0]
            str2 = listTemp[1]
            str3 = listTemp[2]
            str4 = listTemp[3]
            
            strTemp2 = ''
            strTemp21 = ''
            strTemp3 = ''
            strTemp31 = ''
            strTemp4 = ''
            strTemp41 = ''
            cau = ''
            count = 0
            data = []
            socau = 0

            fo = open('/home/namndmk/testXS.txt', 'wb')
            for i in range(0, len(str1)-1):
                for j in range(i+1, len(str1)):
                    count = count + 1;
                    strTemp4 = str4[i]+str4[j]
                    strTemp41 = str4[j]+str4[i]
                    for z in range(2*sogiai, 3*(sogiai)-1):
                        if strTemp4 == c[z] or strTemp41 == c[z]:
                           strTemp3 = str3[i]+str3[j]
                           strTemp31 = str3[j]+str3[i]
                           for x in range(sogiai, (2*sogiai)-1):
                               if strTemp3 == c[x] or strTemp31 == c[x]:
                                  strTemp2 = str2[i]+str2[j]
                                  strTemp21 = str2[j]+str2[i]
                                  for y in range(0, sogiai-1):
                                      
                                      if strTemp2 == c[y] or strTemp21 == c[y]:
                                         doc['lastUpdate'] = listKq[0]['dateobj']
                                         #doc['timestamp'] = str(time.time())
                                         doc['songaycauchay'] = 3
                                         doc['_id'] = getMD5Hash(str1[i]+str1[j]+str(doc['lastUpdate'])+doc['xoso'])
                                         cau = str1[i] + str1[j]
                                         if coll.find_one({'_id':doc['_id']}):
                                             print 'Cầu: ',cau, ' da ton tai trong CSDL !'
                                             continue
                                         doc['cau'] = cau
                                         doc['vitri'] = str(i)+'-'+str(j)
                                         #print "Co cau tai vi tri: ", i, j
                                         
                                         #print "Dự đoán số ra lần tới: ", cau
                                         #print  "Cau truoc 1 ngay", str2[i]+str2[j]
                                         #print '--------------------'
                                         coll.save(doc)
                                         cprint('insert thanh cong !','red')
                                         print "Co cau tai vi tri: ", i, j
                                         print "Dự đoán số ra lần tới: ", cau

                                         socau = socau+1
                                         fo.write(cau)
                                         fo.write('\n')
            print count
            print 'so cau: ', socau
        else:
            print "Không kết nối được"

if __name__ == '__main__':
    soiCauXoSo()
    os._exit(1)
